using AdmissionQA.Application.Common;
using AdmissionQA.Application.Dtos.MajorInfo;
using AdmissionQA.Application.ServiceInterfaces;
using AdmissionQA.Domain.Entities;
using AdmissionQA.Domain.Repositorys;
using Microsoft.Extensions.Logging;

namespace AdmissionQA.Application.Services;

/// <summary>
/// 专业信息服务实现
/// </summary>
public class MajorInfoServices(IRepository<MajorInfo> repository, ILogger<MajorInfoServices> logger, ITextEmbeddingService embeddingService)
    : IMajorInfoServices
{
    private readonly IRepository<MajorInfo> _repository = repository;
    private readonly ILogger<MajorInfoServices> _logger = logger;
    private readonly ITextEmbeddingService _embeddingService = embeddingService;

    /// <summary>
    /// 批量创建专业信息
    /// </summary>
    /// <param name="majorInfos">专业信息列表</param>
    /// <returns>创建结果</returns>
    public async Task<Result<string>> CreateMajorInfosAsync(MajorInfosDto majorInfos)
    {
        var infosToCreate = majorInfos
            .MajorInfos.Select(item =>
                MajorInfo.CreateMajorInfo(item.MajorName, item.Courses, item.CareerProspects)
            )
            .Where(item => item != null)
            .Select(item => item!)
            .ToList();

        if (infosToCreate.Count == 0)
        {
            _logger.LogWarning("批量创建专业信息失败：没有有效的信息");
            return Result<string>.Fail("没有有效的专业信息可以创建");
        }

        await _repository.CreateRangeAsync(infosToCreate);
        _logger.LogInformation("批量创建专业信息成功，数量：{Count}", infosToCreate.Count);
        return Result<string>.Success("创建成功");
    }

    /// <summary>
    /// 创建专业信息
    /// </summary>
    /// <param name="majorInfo">专业信息</param>
    /// <returns>创建结果</returns>
    public async Task<Result<string>> CreateMajorInfoAsync(MajorInfoDto majorInfo)
    {
        var info = MajorInfo.CreateMajorInfo(majorInfo.MajorName, majorInfo.Courses, majorInfo.CareerProspects);
        if (info == null)
        {
            _logger.LogWarning("创建专业信息失败，参数：{@MajorInfo}", majorInfo);
            return Result<string>.Fail("创建专业信息失败");
        }
        var content = majorInfo.MajorName + " " + majorInfo.CareerProspects + " " + (majorInfo.Description ?? "");
        info.Embedding = _embeddingService.GetVector(content);
        await _repository.CreateAsync(info);
        _logger.LogInformation("创建专业信息成功，专业：{MajorName}", majorInfo.MajorName);
        return Result<string>.Success("创建成功");
    }

    /// <summary>
    /// 批量删除专业信息
    /// </summary>
    /// <param name="ids">专业信息ID列表</param>
    /// <returns>删除结果</returns>
    public async Task<Result<string>> DeleteMajorInfosAsync(IEnumerable<Guid> ids)
    {
        // 并行获取所有专业信息
        var tasks = ids.Select(id => _repository.GetByIdAsync(id));
        var infos = await Task.WhenAll(tasks);

        // 过滤掉 null 值并转换为非空类型
        var validInfos = infos.OfType<MajorInfo>().ToList();

        // 检查是否有有效的专业信息
        if (validInfos.Count == 0)
        {
            _logger.LogWarning("批量删除专业信息失败：未找到任何信息，ids={@Ids}", ids);
            return Result<string>.Fail("没有找到专业信息");
        }

        // 调用 Delete 方法标记为删除
        foreach (var info in validInfos)
        {
            if (!info.Delete())
            {
                _logger.LogWarning("批量删除专业信息时，信息已被删除，id={Id}", info.Id);
                return Result<string>.Fail($"专业信息 {info.Id} 已经被删除");
            }
        }

        // 更新所有有效的专业信息
        await _repository.UpdateRangeAsync(validInfos);
        _logger.LogInformation("批量删除专业信息成功，数量：{Count}", validInfos.Count);

        return Result<string>.Success("删除成功");
    }

    /// <summary>
    /// 删除专业信息
    /// </summary>
    /// <param name="id">专业信息ID</param>
    /// <returns>删除结果</returns>
    public async Task<Result<string>> DeleteMajorInfoAsync(Guid id)
    {
        var info = await _repository.GetByIdAsync(id);
        if (info == null)
        {
            _logger.LogWarning("删除专业信息失败：未找到信息，id={Id}", id);
            return Result<string>.Fail("没有找到专业信息");
        }
        if (!info.Delete())
        {
            _logger.LogWarning("删除专业信息失败：信息已被删除，id={Id}", id);
            return Result<string>.Fail("专业信息已经被删除");
        }
        await _repository.UpdateAsync(info);
        _logger.LogInformation("删除专业信息成功，id={Id}", id);
        return Result<string>.Success("删除成功");
    }

    /// <summary>
    /// 根据ID获取专业信息
    /// </summary>
    /// <param name="id">专业信息ID</param>
    /// <returns>专业信息</returns>
    public async Task<Result<MajorInfo>> GetMajorInfoByIdAsync(Guid id)
    {
        var info = await _repository.GetByIdAsync(id);
        if (info == null)
        {
            return Result<MajorInfo>.Fail("没有找到专业信息");
        }
        return Result<MajorInfo>.Success(info);
    }

    /// <summary>
    /// 获取专业信息数量
    /// </summary>
    /// <returns>专业信息数量</returns>
    public async Task<int> GetMajorInfoCountAsync()
    {
        return await _repository.GetCountAsync();
    }

    /// <summary>
    /// 获取所有专业信息
    /// </summary>
    /// <returns>专业信息列表</returns>
    public async Task<Result<IEnumerable<MajorInfo>>> GetAllMajorInfosAsync()
    {
        var infos = await _repository.GetAllAsync();
        return Result<IEnumerable<MajorInfo>>.Success(infos);
    }

    /// <summary>
    /// 分页获取专业信息
    /// </summary>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <returns>分页结果</returns>
    public async Task<Result<IEnumerable<MajorInfo>>> GetPagedMajorInfosAsync(
        int pageIndex = 0,
        int pageSize = 10
    )
    {
        var infos = await _repository.GetPagedAsync(pageIndex, pageSize);
        return Result<IEnumerable<MajorInfo>>.Success(infos);
    }

    /// <summary>
    /// 根据名称搜索专业信息
    /// </summary>
    /// <param name="majorName">专业名称</param>
    /// <returns>匹配的专业信息列表</returns>
    public async Task<Result<IEnumerable<MajorInfo>>> SearchMajorInfosByNameAsync(string majorName)
    {
        var infos = await _repository.GetListConditionAsync(item =>
            item.MajorName.Contains(majorName)
        );
        return Result<IEnumerable<MajorInfo>>.Success(infos);
    }

    /// <summary>
    /// 更新专业信息
    /// </summary>
    /// <param name="id">专业信息ID</param>
    /// <param name="majorInfo">专业信息</param>
    public async Task<Result<string>> UpdateMajorInfoAsync(Guid id, MajorInfoDto majorInfo)
    {
        var info = await _repository.GetByIdAsync(id);
        if (info == null)
        {
            _logger.LogWarning("更新专业信息失败：未找到信息，id={Id}", id);
            return Result<string>.Fail("没有找到专业信息");
        }
        info.UpdateMajorInfo(majorInfo.MajorName, majorInfo.Courses, majorInfo.CareerProspects, majorInfo.Description);
        var content = majorInfo.MajorName + " " + majorInfo.CareerProspects + " " + (majorInfo.Description ?? "");
        info.Embedding = _embeddingService.GetVector(content);
        await _repository.UpdateAsync(info);
        _logger.LogInformation("更新专业信息成功，id={Id}", id);
        return Result<string>.Success("更新成功");
    }

    public async Task<Result<IEnumerable<MajorInfo>>> SearchMajorInfosByEmbeddingAsync(string text, int topK = 5)
    {
        var queryEmbedding = _embeddingService.GetVector(text);
        var all = await _repository.GetAllAsync();
        var withScore = all.Where(x => x.Embedding != null)
            .Select(x => new { Entity = x, Score = CosineSimilarity(queryEmbedding, x.Embedding!) })
            .OrderByDescending(x => x.Score)
            .Take(topK)
            .Select(x => x.Entity)
            .ToList();
        return Result<IEnumerable<MajorInfo>>.Success(withScore);
    }
    private static float CosineSimilarity(float[] v1, float[] v2)
    {
        if (v1 == null || v2 == null || v1.Length != v2.Length) return 0f;
        float dot = 0, norm1 = 0, norm2 = 0;
        for (int i = 0; i < v1.Length; i++)
        {
            dot += v1[i] * v2[i];
            norm1 += v1[i] * v1[i];
            norm2 += v2[i] * v2[i];
        }
        if (norm1 == 0 || norm2 == 0) return 0f;
        return dot / (float)(Math.Sqrt(norm1) * Math.Sqrt(norm2));
    }
}
